package com.tangcheng.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.JdbcUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: cheng.tang
 * @Date: 2023/9/13
 * @Description: mybatis-subject
 */
@Slf4j
public class DruidBaseExample {

    public static void main(String[] args) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/tqcs?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("myspace2022");
        dataSource.setInitialSize(1);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(3);
        dataSource.setMaxWait(60000);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setValidationQuery("SELECT 1 FROM DUAL");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        ThreadPoolExecutor threadPoolExecutor = buildExecutor();
        recordLog(dataSource);
        for (int i = 0; i < 20; i++) {
            doTask(dataSource);
        }
    }

    private static ThreadPoolExecutor buildExecutor() {
        ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(100);
        ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
        return new ThreadPoolExecutor(10, 100, 60, TimeUnit.SECONDS, workQueue, callerRunsPolicy);
    }

    private static void recordLog(DruidDataSource dataSource) {
        if (dataSource == null) {
            return;
        }
        List<Map<String, Object>> poolingConnectionInfo = dataSource.getPoolingConnectionInfo();
        for (Map<String, Object> stringObjectMap : poolingConnectionInfo) {
            for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
            }
        }
    }

    private static void doTask(DruidDataSource dataSource) {
        try {
            // 获取连接
            Connection conn = dataSource.getConnection();
            // 创建语句
            Statement stmt = conn.createStatement();
            // 执行查询
            String sql = "SELECT * FROM task";
            ResultSet rs = stmt.executeQuery(sql);
            // 获取结果集元数据
            ResultSetMetaData metaData = rs.getMetaData();
            // 打印字段名
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                System.out.printf("%-30s", metaData.getColumnName(i));
            }
            System.out.println();
            // 打印查到的数据
            while (rs.next()) {
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    System.out.printf("%-30s", rs.getString(i));
                }
                System.out.println();
            }
            // 关闭连接等资源
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(dataSource);
        }

        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException ignored) {
        }
    }


}
